package com.irdstudio.basic.framework.core.util;

import java.math.BigInteger;
import java.security.Key;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.RSAPublicKeySpec;
import java.security.spec.X509EncodedKeySpec;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

import com.irdstudio.basic.framework.core.constant.PubConstant;

public final class RSAUtility {
	
	/**
	 * 密钥算法
	 */
	public static final String RSA_KEY_ALGORITHM = "RSA";
	
	/**
	 * 加解密算法/工作模式/填充方式
	 */
	public static final String CIPHER_ALGORITHM = "RSA/ECB/PKCS1Padding";
	
	static java.util.Base64.Encoder encoder = java.util.Base64.getEncoder();
	 /**
     * 获取非对称加密算法的密钥
     * @param alg 加密算法枚举
     * @return 16进制的密钥数组
     * @throws
     * */
    public final static KeyPair getDefaultKeyPair() throws Exception{
        KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(RSA_KEY_ALGORITHM);
        //密钥位数
        keyPairGen.initialize(1024);
        //密钥对
        return keyPairGen.generateKeyPair();
    }
    
    /**
     * 获得公钥字符串
     * @param modulus
     * @param exponent
     * @return
     */
    public static RSAPublicKey getPublicKey(String modulus, String exponent) {
		try {
			KeyFactory keyFactory = KeyFactory.getInstance("RSA");
			RSAPublicKeySpec keySpec = new RSAPublicKeySpec(new BigInteger(modulus, 16), new BigInteger(exponent, 16));
			return (RSAPublicKey) keyFactory.generatePublic(keySpec);
		} catch (Exception e) {}
		return null;
	}
    
    /**
     * 公钥串
     * @param key
     * @return
     * @throws Exception
     */
    public static PublicKey getPublicKey(String key) throws Exception {
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(Base64.decode(key));
        KeyFactory keyFactory = KeyFactory.getInstance(RSA_KEY_ALGORITHM);
        return keyFactory.generatePublic(keySpec);
	}
    
    /**
     * 私钥串
     * @param key
     * @return
     * @throws Exception
     */
    public static PrivateKey getPrivateKey(String key) throws Exception {
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(Base64.decode(key));
        KeyFactory keyFactory = KeyFactory.getInstance(RSA_KEY_ALGORITHM);
        return keyFactory.generatePrivate(keySpec);
	}
    
    /**
     * 非对称加密方法
     * @param plainText
     * @param key
     * @return
     * @throws Exception
     */
    public static String encrypt2hex(String str, Key key) throws Exception{
        return CrypticUtility.byte2hex(encrypt(str.getBytes(PubConstant.CHARSET_UTF_8), key));
    }
    
    /**
     * 对称加密方法
     * @param plainText
     * @param key
     * @return
     * @throws Exception
     */
    public static String encrypt2hex(String str, byte[] key) throws Exception{
        return CrypticUtility.byte2hex(encrypt(CrypticUtility.getEncByteFromStr(str), key));
    }
    
    public static String encryptByBase64(String str, String key) throws Exception{
        return new String(encoder.encode(encrypt(CrypticUtility.getEncByteFromStr(str), getPublicKey(key))));
    }
    
    public static String encryptByBase64(String str, Key key) throws Exception{
        return new String(encoder.encode(encrypt(CrypticUtility.getEncByteFromStr(str), key)));
    }
    
    /**
     * 对称加密方法
     * @param plainText 明文的16进制字节数组
     * @param encrytKey 16进制的密钥数组
     * @param alg 加密算法的枚举
     * @return 加密结果，返回加密后的字节数组
     * @throws Exception
     * */
    public static byte[] encrypt(byte[] str, byte[] encrytKey) throws Exception{
        return encrypt(str, new SecretKeySpec(encrytKey, CIPHER_ALGORITHM));
    }

    /**
     * 非对称加密方法
     * @param plainText 明文的16进制字节数组
     * @param key 通过KeyPair获得的公钥
     * @return 加密结果，返回加密后的字节数组
     * @throws Exception
     * */
    public static byte[] encrypt(byte[] plainText, Key key) throws Exception{
        Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE, key);
        return cipher.doFinal(plainText);
    }
    
    /**
     * 对称解密
     * @param str
     * @param key
     * @return
     * @throws Exception
     */
    public static String decrypt2hex(String str, byte[] key) throws Exception{
        return CrypticUtility.byte2hex(decrypt(CrypticUtility.getEncByteFromStr(str), key));
    }
    
    /**
     * 对称解密方法
     * @param ciperText 密文的16进制字节数组
     * @param decrytKey 16进制的密钥数组
     * @param alg 加密算法的枚举
     * @return 解密结果，返回解密后的字节数组
     * @throws Exception
     * */
    public static byte[] decrypt(byte[] ciperText, byte[] decrytKey) throws Exception{
        return decrypt(ciperText, new SecretKeySpec(decrytKey, CIPHER_ALGORITHM));
    }
    
    /**
     * 非对称解密
     * @param str
     * @param key
     * @return
     * @throws Exception
     */
    public static String decrypt2hex(String str, Key key) throws Exception{
        return new String(decrypt(CrypticUtility.hex2byte(str.getBytes(PubConstant.CHARSET_UTF_8)), key), PubConstant.CHARSET_UTF_8);
    }
    
    public static String decryptByBase64(String str, String key) throws Exception{
        return new String(decrypt(Base64.decode(str), getPrivateKey(key)), PubConstant.CHARSET_UTF_8);
    }
    
    public static String decryptByBase64(String str, Key key) throws Exception{
        return new String(decrypt(Base64.decode(str), key), PubConstant.CHARSET_UTF_8);
    }
    
    /**
     * 非对称加密解密方法
     * @param ciperText 密文的16进制字节数组
     * @param key 通过keypair得到的非对称加密私钥
     * @return 解密结果，返回解密后的字节数组
     * @throws Exception
     * */
    public static byte[] decrypt(byte[] ciperText, Key key) throws Exception{
        Cipher cipher = Cipher.getInstance(RSA_KEY_ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE, key);
        return cipher.doFinal(ciperText);
    }
    
    public static void main(String[] args) throws Exception {
		String publicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCHDmTC9EMBbR55wuaUfzsSXBnWZQCNLkcmnGIlS6GF6Ln44X7tK90pPdrgGrUUNaznrjQck0KMYpFGHilBkeUF0SH8agHPjUHv+C+I5HiTqNBO7mmkP1tEerLdKGWRXN16e7dW7opoukzq+CuaThcmVaSIDxArvOLokP7/z63J7wIDAQAB";
		String privateKey = "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAIcOZML0QwFtHnnC5pR/OxJcGdZlAI0uRyacYiVLoYXoufjhfu0r3Sk92uAatRQ1rOeuNByTQoxikUYeKUGR5QXRIfxqAc+NQe/4L4jkeJOo0E7uaaQ/W0R6st0oZZFc3Xp7t1buimi6TOr4K5pOFyZVpIgPECu84uiQ/v/PrcnvAgMBAAECgYA+6K54vQyFGo3qi6WaIBWk/K+wVQXHvXm4+3kgBDWtyXTvACJ+WUNAVaahYu9cBZCPrm5prRJ/j945eg0flNTHinlH+0ame4pbRJp4b26jmzuv/Vf2ut7fmcS5KfRV5dhxAXb+mKNsLqydRssUSKAp/fou7+M9fZOoT4t3GKc9IQJBAOdxr/76/Fi7Ctqc/woJP8p6qyMxy/xzNAhrJZkz7bZtQHIlahwpGCYaibz0cXXDPR6+YxQLbD2tUpjxrxg+FpECQQCVYrDCsFVpzf5GHvqUNbCvnzeFjCg9fhHEGY10ssKRYNTLNASXQi/3AKjWCyYp+otdhgZNy6LVxMC8Z3WqExh/AkAu7h2a3XfX4i2EQLtyZIe73f3fyBQt34pYfqmEFESKbkLYIoAOr8KGz3DIkOSE1Y8KMd7TTLGpHAEYpEE18DkRAkATMeQukAPZnYtvrSlbg+6ZEmdK9LBy/lEAFpxzg0i2729IUP3KBcot/dqz7ijQOg5QTRlgQ6s/tpFhZBXdbai3AkEAiWn4ubTEG48xViyvf/9iud3dANfuvvBjg0kikCfnddncFGmna0PG9IEF2kP03G6Gowh4w58VX1BFR+Xrn8Ke+g==";
		
		String username = encryptByBase64("efp_daybat_opr", publicKey);
    	System.out.println(username);
		System.out.println("----------------------------------------");
		String password = encryptByBase64("Daybat@123456", publicKey);
		System.out.println(password);
    }
    
}
